package com.github.axet.audiorecorder.simple.activities

import android.Manifest
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Environment
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.widget.Toast
import com.github.axet.audiorecorder.library.recorder.SimpleRecordingManager
import com.github.axet.audiorecorder.library.services.SimpleRecordingService
import com.github.axet.audiorecorder.simple.R
import com.github.axet.audiorecorder.simple.databinding.ActivitySimpleRecordingBinding
import java.io.File

class SimpleRecordingActivity : Activity() {
    
    companion object {
        private const val TAG = "SimpleRecordingActivity"
        private const val PERMISSION_REQUEST_CODE = 1001
        
        private val REQUIRED_PERMISSIONS = arrayOf(
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
        )
    }
    
    private lateinit var binding: ActivitySimpleRecordingBinding
    private var isRecording = false
    private lateinit var recordingManager: SimpleRecordingManager
    private lateinit var dir: String
    private val recordingReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val status = intent?.getStringExtra("status")
            
            when (status) {
                "recording" -> {
                    val recordingTime = intent.getLongExtra(SimpleRecordingService.EXTRA_RECORDING_TIME, 0)
                    updateRecordingTime(recordingTime)
                }
                "stopped" -> {
                    val filePath = intent.getStringExtra(SimpleRecordingService.EXTRA_RECORDING_FILE)
                    onRecordingStopped(filePath)
                }
                "error" -> {
                    val errorMessage = intent.getStringExtra(SimpleRecordingService.EXTRA_ERROR_MESSAGE)
                    onRecordingError(errorMessage)
                }
            }
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySimpleRecordingBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        initViews()
        recordingManager = SimpleRecordingManager(this)
        dir = Environment.getExternalStorageDirectory().path + "/myfoler/SimpleAudioRecorder"
        recordingManager.setStoragePath(dir)
        
        if (checkPermissions()) {
            initializeApp()
        } else {
            requestPermissions()
        }
    }
    
    private fun initViews() {
        binding.recordButton.setOnClickListener { toggleRecording() }
    }
    
    private fun initializeApp() {
        File(dir).mkdirs()
        updateUI()
    }
    
    private fun checkPermissions(): Boolean {
        return REQUIRED_PERMISSIONS.all { permission ->
            ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
        }
    }
    
    private fun requestPermissions() {
        ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, PERMISSION_REQUEST_CODE)
    }
    
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        
        if (requestCode == PERMISSION_REQUEST_CODE) {
            val allGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }
            
            if (allGranted) {
                initializeApp()
            } else {
                Toast.makeText(this, R.string.permission_required, Toast.LENGTH_LONG).show()
                finish()
            }
        }
    }
    
    private fun toggleRecording() {
        if (isRecording) {
            stopRecording()
        } else {
            startRecording()
        }
    }
    
    private fun startRecording() {
        recordingManager.startRecording()
        isRecording = true
        updateUI()
    }
    
    private fun stopRecording() {
        recordingManager.stopRecording()
        isRecording = false
        updateUI()
    }
    
    private fun updateUI() {
        if (isRecording) {
            binding.statusText.setText(R.string.recording)
            binding.recordButton.setText(R.string.stop_recording)
            binding.recordButton.setBackgroundResource(android.R.drawable.btn_default)
        } else {
            binding.statusText.setText(R.string.app_name)
            binding.recordButton.setText(R.string.start_recording)
            binding.recordButton.setBackgroundResource(R.drawable.record_button_background)
            binding.timeText.text = "00:00"
        }
        
        // 更新配置信息显示
        updateConfigDisplay()
    }
    
    private fun updateRecordingTime(timeMs: Long) {
        val seconds = (timeMs / 1000).toInt()
        val minutes = seconds / 60
        val remainingSeconds = seconds % 60
        
        val timeString = String.format("%02d:%02d", minutes, remainingSeconds)
        binding.timeText.text = timeString
    }
    
    private fun onRecordingStopped(filePath: String?) {
        isRecording = false
        updateUI()
        
        filePath?.let {
            val file = File(it)
            val message = getString(R.string.recording_saved, file.name)
            Toast.makeText(this, message, Toast.LENGTH_LONG).show()
        }
    }
    
    private fun onRecordingError(errorMessage: String?) {
        isRecording = false
        updateUI()
        
        val message = getString(R.string.recording_error, errorMessage ?: "Unknown error")
        Toast.makeText(this, message, Toast.LENGTH_LONG).show()
    }
    
    private fun updateConfigDisplay() {
        val configInfo = recordingManager.getConfigDisplayText()
        
        // 添加录音统计信息
        val stats = recordingManager.getStorage().getRecordingStats()
        val displayText = if (stats.fileCount > 0) {
            "$configInfo\n已有 ${stats.fileCount} 个录音文件 (${stats.getFormattedSize()})"
        } else {
            configInfo
        }
        
        binding.configText.text = displayText
    }
    
    override fun onResume() {
        super.onResume()
        val filter = IntentFilter(SimpleRecordingService.ACTION_RECORDING_STATUS)
        registerReceiver(recordingReceiver, filter)
    }
    
    override fun onPause() {
        super.onPause()
        unregisterReceiver(recordingReceiver)
    }
}